<template>
  <view class="detail-container">
    <!-- 头部标题 -->
    <view class="detail-header">
      <view class="header-content">
        <text class="detail-title">停工日志详情</text>
        <text class="detail-subtitle">{{ getDateOnly(detailForm.meetingDate) + '日停工日志' }}</text>
      </view>
    </view>

    <!-- 详情内容 -->
    <view class="detail-content">
      <!-- 基本信息 -->
      <view class="detail-section">
        <view class="section-header">
          <uni-icons type="chat" size="20" color="#007AFF"></uni-icons>
          <text class="section-title">基本信息</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item">
            <text class="detail-label">停工日期</text>
            <text class="detail-value">{{ getDateOnly(detailForm.meetingDate) || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">项目</text>
            <text class="detail-value">{{ getProjectNameById(detailForm.projectId) || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">天气</text>
            <text class="detail-value">{{ detailForm.weather || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">管理人员数量</text>
            <text class="detail-value">{{ detailForm.managerCount || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">班组成员数量</text>
            <text class="detail-value">{{ detailForm.teamMemberCount || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">桩基设备型号</text>
            <text class="detail-value">{{ detailForm.baseDeviceModel || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">桩基设备数量</text>
            <text class="detail-value">{{ detailForm.baseDeviceCount || '-' }}</text>
          </view>
        </view>
      </view>

      <!-- 当日巡查情况 -->
      <view class="detail-section">
        <view class="section-header">
          <uni-icons type="loop" size="20" color="#52c41a"></uni-icons>
          <text class="section-title">当日巡查情况</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item">
            <text class="detail-label">巡查频次</text>
            <text class="detail-value">{{ detailForm.patrolFrequency || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">巡查时段</text>
            <text class="detail-value">{{ detailForm.patrolPeriod || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">异常情况</text>
            <view class="detail-value">
              <text class="status-badge" :class="isAbnormalClass">
                {{ detailForm.isAbnormal === 1 ? '正常' : '异常' }}
              </text>
            </view>
          </view>
          <view class="detail-item full-width" v-if="detailForm.isAbnormal !== 1">
            <text class="detail-label">异常情况说明</text>
            <text class="detail-value text-content">{{ detailForm.abnormalDescription || '-' }}</text>
          </view>
        </view>
      </view>

      <!-- 监控设备状态 -->
      <view class="detail-section">
        <view class="section-header">
          <uni-icons type="videocam" size="20" color="#fa8c16"></uni-icons>
          <text class="section-title">监控设备状态</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item">
            <text class="detail-label">监控设备状态</text>
            <view class="detail-value">
              <text class="status-badge" :class="monitorStatusClass">
                {{ detailForm.monitorStatus === 1 ? '正常' : '故障' }}
              </text>
            </view>
          </view>
          <view class="detail-item full-width" v-if="detailForm.monitorStatus !== 1">
            <text class="detail-label">故障说明</text>
            <text class="detail-value text-content">{{ detailForm.faultDescription || '-' }}</text>
          </view>
        </view>
      </view>

      <!-- 其他说明 -->
      <view class="detail-section" v-if="detailForm.remark">
        <view class="section-header">
          <uni-icons type="calendar" size="20" color="#1890ff"></uni-icons>
          <text class="section-title">其他补充说明</text>
        </view>
        <view class="detail-grid">
          <view class="detail-item full-width">
            <text class="detail-value text-content">{{ detailForm.remark || '-' }}</text>
          </view>
        </view>
      </view>

      <view class="detail-section" v-if="detailImages.length">
        <view class="section-header">
          <uni-icons type="image" size="20" color="#1890ff"></uni-icons>
          <text class="section-title">巡查照片</text>
        </view>
        <view class="detail-image-grid">
          <view class="detail-image-item" v-for="(image, index) in detailImages" :key="image.originalPath || index"
            @click="previewDetailImage(index)">
            <image :src="image.url" mode="aspectFill"></image>
          </view>
        </view>
      </view>

      <view class="detail-section" v-if="detailFiles.length">
        <view class="section-header">
          <uni-icons type="paperclip" size="20" color="#fa541c"></uni-icons>
          <text class="section-title">附件信息</text>
        </view>
        <view class="detail-attachment-list">
          <view class="attachment-row" v-for="(file, index) in detailFiles" :key="file.originalPath || index">
            <view class="attachment-info">
              <uni-icons type="paperplane" size="18" color="#007AFF"></uni-icons>
              <text class="attachment-name">{{ file.fileName }}</text>
            </view>
            <view class="attachment-actions">
              <text class="attachment-action" @click="handleDetailFilePreview(file)">预览</text>
            </view>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import { listAllProjectContractInfo, getBizStoppageLog } from '@/api/production/index'
import { fileLinkTransfer } from '@/api/production/file'

export default {
  data() {
    return {
      detailForm: {},
      projectList: [],
      projectIdToName: {},
      detailImages: [],
      detailFiles: []
    }
  },
  computed: {
    // 异常情况样式类
    isAbnormalClass() {
      if (this.detailForm.isAbnormal === 1) return 'status-normal'
      return 'status-warning'
    },
    // 监控设备状态样式类
    monitorStatusClass() {
      if (this.detailForm.monitorStatus === 1) return 'status-normal'
      return 'status-warning'
    }
  },
  onLoad(options) {
    if (options.id) {
      this.loadDetailData(options.id)
    }
    this.loadProjectList()
  },
  methods: {
    // 加载详情数据
    async loadDetailData(id) {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const response = await getBizStoppageLog(id)
        const data = response.data || response
        // 规范化状态字段
        this.detailForm = {
          ...data,
          isAbnormal: this.normalizeStatusValue(data.isAbnormal),
          monitorStatus: this.normalizeStatusValue(data.monitorStatus),
          imageList: this.normalizeImageListData(data.imageList)
        }
        await this.processDetailAttachments()
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取详情失败:', error)
        uni.showToast({
          title: '获取详情失败',
          icon: 'none'
        })
      }
    },

    // 规范化状态值
    normalizeStatusValue(value) {
      if (value === undefined || value === null || value === '') {
        return 1
      }
      const parsed = Number(value)
      return Number.isNaN(parsed) ? 1 : parsed
    },

    // 加载项目列表
    async loadProjectList() {
      try {
        const response = await listAllProjectContractInfo()
        const list = response.data || []
        this.projectList = list
        // 构建项目ID到名称的映射
        this.projectIdToName = {}
        list.forEach(item => {
          this.projectIdToName[item.id] = item.projectName
        })
      } catch (error) {
        console.error('获取项目列表失败:', error)
      }
    },

    // 根据项目ID获取项目名称
    getProjectNameById(projectId) {
      return this.projectIdToName[projectId] || projectId
    },

    // 只保留年月日
    getDateOnly(datetime) {
      if (!datetime) return ''
      const str = typeof datetime === 'string' ? datetime : this.changeTime(datetime)
      const match = str.match(/^\d{4}-\d{2}-\d{2}/)
      return match ? match[0] : str
    },

    // 时间格式化
    changeTime(time) {
      if (!time) return ''
      const date = new Date(time)
      if (isNaN(date.getTime())) return time
      const pad = n => n < 10 ? '0' + n : n
      const y = date.getFullYear()
      const m = pad(date.getMonth() + 1)
      const d = pad(date.getDate())
      const h = pad(date.getHours())
      const min = pad(date.getMinutes())
      const s = pad(date.getSeconds())
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    },

    normalizeImageListData(imageList) {
      if (!imageList) return []
      if (Array.isArray(imageList)) {
        return imageList.filter(item => !!item)
      }
      if (typeof imageList === 'string') {
        try {
          const parsed = JSON.parse(imageList)
          if (Array.isArray(parsed)) {
            return parsed.filter(item => !!item)
          }
        } catch (error) {
          return imageList.split(',').map(item => item.trim()).filter(item => !!item)
        }
      }
      return []
    },

    getFileNameFromPath(path) {
      if (!path) return ''
      const segments = path.split('/')
      return segments[segments.length - 1] || path
    },

    getFileExtension(fileName) {
      if (!fileName || fileName.indexOf('.') === -1) return ''
      return fileName.split('.').pop().toLowerCase()
    },

    isImageFile(fileName = '') {
      const imageExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
      return imageExt.includes(this.getFileExtension(fileName))
    },

    async transformToDisplayUrl(path) {
      if (!path) return ''
      try {
        const res = await fileLinkTransfer(path)
        if (res?.data?.url) {
          return res.data.url
        }
      } catch (error) {
        console.error('文件链接转换失败:', error)
      }
      return path
    },

    async processDetailAttachments() {
      const list = this.detailForm.imageList || []
      if (!list.length) {
        this.detailImages = []
        this.detailFiles = []
        return
      }
      const mapped = await Promise.all(list.map(async (path) => {
        const fileName = this.getFileNameFromPath(path)
        const displayUrl = await this.transformToDisplayUrl(path)
        if (this.isImageFile(fileName)) {
          return {
            type: 'image',
            data: { originalPath: path, url: displayUrl }
          }
        }
        return {
          type: 'file',
          data: { originalPath: path, fileName, displayUrl }
        }
      }))
      this.detailImages = mapped.filter(item => item.type === 'image').map(item => item.data)
      this.detailFiles = mapped.filter(item => item.type === 'file').map(item => item.data)
    },

    async previewDetailImage(index) {
      if (!this.detailImages.length) return
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const urls = await Promise.all(this.detailImages.map(async (item) => {
          const origin = item.originalPath || item.url
          return this.transformToDisplayUrl(origin)
        }))
        const current = urls[index] || urls[0]
        uni.previewImage({
          urls,
          current
        })
      } catch (error) {
        console.error('图片预览失败:', error)
        uni.showToast({
          title: '预览失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    async handleDetailFilePreview(file) {
      if (!file?.originalPath) return
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const url = await this.transformToDisplayUrl(file.originalPath)
        await this.openDocumentFromUrl(url, file.fileName)
      } catch (error) {
        console.error('附件预览失败:', error)
        uni.showToast({
          title: '预览失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    async openDocumentFromUrl(url, fileName) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url,
          success: (downloadRes) => {
            if (downloadRes.statusCode === 200) {
              uni.openDocument({
                filePath: downloadRes.tempFilePath,
                showMenu: true,
                fileType: this.getFileExtension(fileName),
                success: resolve,
                fail: reject
              })
            } else {
              reject(new Error('下载失败'))
            }
          },
          fail: reject
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.detail-header {
  background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  position: relative;
}

.header-content {
  text-align: center;
}

.detail-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.detail-subtitle {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
}

.detail-content {
  padding: 30rpx;
}

.detail-section {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #eee;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-left: 15rpx;
}

.detail-grid {
  padding: 30rpx;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.detail-item.full-width {
  flex-direction: column;
  width: 100%;
}

.detail-item.full-width .detail-value {
  width: 100%;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
  min-width: 200rpx;
  margin-right: 20rpx;
  line-height: 1.5;
}

.detail-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  word-break: break-all;
}

.text-content {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-top: 15rpx;
  white-space: pre-wrap;
  width: 100%;
  box-sizing: border-box;
}

.detail-value.text-content {
  display: block;
  width: 100%;
}

.status-badge {
  display: inline-block;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-normal {
  background: #f6ffed;
  color: #52c41a;
  border: 1rpx solid #b7eb8f;
}

.status-warning {
  background: #fff7e6;
  color: #fa8c16;
  border: 1rpx solid #ffd591;
}

.detail-image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  padding: 20rpx 30rpx 30rpx;
}

.detail-image-item {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
  border: 1rpx solid #e5e5e5;
}

.detail-image-item image {
  width: 100%;
  height: 100%;
}

.detail-attachment-list {
  padding: 20rpx 30rpx 30rpx;
}

.detail-attachment-list .attachment-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-attachment-list .attachment-row:last-child {
  border-bottom: none;
}

.detail-attachment-list .attachment-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex: 1;
  min-width: 0;
}

.attachment-name {
  font-size: 26rpx;
  color: #333;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.attachment-actions {
  font-size: 26rpx;
  color: #007AFF;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .detail-content {
    padding: 20rpx;
  }

  .detail-grid {
    padding: 20rpx;
  }

  .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .detail-label {
    min-width: auto;
    margin-right: 0;
    margin-bottom: 10rpx;
  }
}
</style>

